// Boss类 - 最终关卡的大BOSS
class Boss {
    constructor(x, y, type = 'principal') {
        try {
            this.x = x || 500;
            this.y = y || 375;
            this.type = type || 'principal';
            this.radius = 40; // 更大的碰撞半径
            
            const stats = this.getBossStats(this.type);
            this.health = stats.health;
            this.maxHealth = this.health;
            this.speed = stats.speed;
            this.damage = stats.damage;
        
            // Boss状态
            this.state = 'spawning'; // 'spawning', 'walking', 'attacking', 'special', 'dying'
            this.phase = 1; // Boss阶段
            this.target = null;
            this.lastAttackTime = 0;
            this.attackCooldown = 2000;
            this.specialAttackCooldown = 5000;
            this.lastSpecialAttack = 0;
            
            // 动画
            this.animationFrame = 0;
            this.animationTime = 0;
            this.facing = 0;
            this.size = 60; // Boss尺寸
            
            // 特殊能力
            this.canSummonZombies = true;
            this.canShootProjectiles = true;
            this.minions = []; // 召唤的小僵尸
            
            // 生成动画
            this.spawnTime = Date.now();
            this.spawnDuration = 3000;
            this.isInvulnerable = true;
            
            // 视觉效果
            this.bloodStains = [];
            this.aura = { radius: 0, color: '#FF0000', alpha: 0.3 };
            
            console.log('Boss创建:', this.type, '血量:', this.health);
        } catch (error) {
            console.error('Boss构造失败:', error);
            throw error;
        }
    }
    
    getBossStats(type) {
        const stats = {
            'principal': {
                name: '校长僵尸',
                health: 500,
                speed: 60,
                damage: 40,
                color: '#2F4F4F',
                specialAbilities: ['summon', 'projectile', 'rage']
            }
        };
        return stats[type] || stats['principal'];
    }
    
    update(deltaTime, player) {
        this.updateState(deltaTime, player);
        this.updateAnimation(deltaTime);
        this.updateMinions(deltaTime, player);
        this.updateAura(deltaTime);
        
        // 检查阶段切换
        this.checkPhaseTransition();
    }
    
    updateState(deltaTime, player) {
        if (!player) return;
        
        const currentTime = Date.now();
        const distToPlayer = Math.sqrt(
            Math.pow(this.x - player.x, 2) + Math.pow(this.y - player.y, 2)
        );
        
        switch (this.state) {
            case 'spawning':
                this.handleSpawning(currentTime);
                break;
                
            case 'walking':
                this.moveTowardsPlayer(deltaTime, player);
                if (distToPlayer < 80) {
                    this.state = 'attacking';
                }
                // 特殊攻击
                if (currentTime - this.lastSpecialAttack > this.specialAttackCooldown) {
                    this.state = 'special';
                }
                break;
                
            case 'attacking':
                this.performAttack(currentTime, player);
                if (distToPlayer > 100) {
                    this.state = 'walking';
                }
                break;
                
            case 'special':
                this.performSpecialAttack(currentTime);
                break;
                
            case 'dying':
                this.handleDeath(deltaTime);
                break;
        }
    }
    
    handleSpawning(currentTime) {
        if (currentTime - this.spawnTime > this.spawnDuration) {
            this.state = 'walking';
            this.isInvulnerable = false;
            
            // 生成震撼效果
            try {
                if (window.gameEngine && typeof Particle !== 'undefined') {
                    for (let i = 0; i < 20; i++) {
                        window.gameEngine.particles.push(new Particle(
                            this.x + (Math.random() - 0.5) * 100,
                            this.y + (Math.random() - 0.5) * 100,
                            (Math.random() - 0.5) * 200,
                            (Math.random() - 0.5) * 200,
                            '#FF4500',
                            2000
                        ));
                    }
                }
            } catch (error) {
                console.error('创建生成特效失败:', error);
            }
        }
    }
    
    moveTowardsPlayer(deltaTime, player) {
        const dx = player.x - this.x;
        const dy = player.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance > 0) {
            const dirX = dx / distance;
            const dirY = dy / distance;
            
            this.x += dirX * this.speed * deltaTime / 1000;
            this.y += dirY * this.speed * deltaTime / 1000;
            this.facing = Math.atan2(dy, dx);
        }
    }
    
    performAttack(currentTime, player) {
        if (currentTime - this.lastAttackTime > this.attackCooldown) {
            this.lastAttackTime = currentTime;
            
            // 近战攻击 - 将在碰撞检测中处理
            this.createAttackEffect();
        }
    }
    
    performSpecialAttack(currentTime) {
        this.lastSpecialAttack = currentTime;
        
        const random = Math.random();
        if (random < 0.4) {
            this.summonZombies();
        } else if (random < 0.8) {
            this.shootProjectiles();
        } else {
            this.rageMode();
        }
        
        this.state = 'walking';
    }
    
    summonZombies() {
        try {
            console.log('Boss召唤僵尸!');
            const numMinions = 3 + this.phase;
            
            for (let i = 0; i < numMinions; i++) {
                const angle = (Math.PI * 2 / numMinions) * i;
                const distance = 80;
                const minionX = this.x + Math.cos(angle) * distance;
                const minionY = this.y + Math.sin(angle) * distance;
                
                // 检查Zombie类是否可用
                if (typeof Zombie === 'undefined') {
                    console.error('Zombie类未定义');
                    continue;
                }
                
                const minion = new Zombie(minionX, minionY, 'fast');
                this.minions.push(minion);
                
                if (window.gameEngine && window.gameEngine.zombies) {
                    window.gameEngine.zombies.push(minion);
                }
            }
            
            // 召唤特效
            this.createSummonEffect();
        } catch (error) {
            console.error('Boss召唤僵尸失败:', error);
        }
    }
    
    shootProjectiles() {
        try {
            console.log('Boss发射投射物!');
            if (!window.player) return;
            
            const numProjectiles = 5;
            for (let i = 0; i < numProjectiles; i++) {
                const angle = Math.atan2(window.player.y - this.y, window.player.x - this.x) + 
                             (Math.random() - 0.5) * Math.PI / 3;
                
                const projectile = new BossProjectile(
                    this.x, this.y,
                    Math.cos(angle) * 200,
                    Math.sin(angle) * 200,
                    this.damage
                );
                
                if (window.gameEngine) {
                    window.gameEngine.bossProjectiles = window.gameEngine.bossProjectiles || [];
                    window.gameEngine.bossProjectiles.push(projectile);
                }
            }
        } catch (error) {
            console.error('Boss发射投射物失败:', error);
        }
    }
    
    rageMode() {
        console.log('Boss进入狂暴模式!');
        this.speed *= 1.5;
        this.attackCooldown *= 0.5;
        this.aura.color = '#FF0000';
        this.aura.alpha = 0.6;
        
        // 3秒后恢复
        setTimeout(() => {
            this.speed /= 1.5;
            this.attackCooldown *= 2;
            this.aura.color = '#FF4500';
            this.aura.alpha = 0.3;
        }, 3000);
    }
    
    takeDamage(damage) {
        if (this.isInvulnerable) return;
        
        this.health -= damage;
        this.addBloodStain();
        
        if (this.health <= 0) {
            this.die();
        }
    }
    
    die() {
        this.state = 'dying';
        
        // 死亡特效
        try {
            if (window.gameEngine && typeof Particle !== 'undefined') {
                for (let i = 0; i < 30; i++) {
                    window.gameEngine.particles.push(new Particle(
                        this.x + (Math.random() - 0.5) * this.size,
                        this.y + (Math.random() - 0.5) * this.size,
                        (Math.random() - 0.5) * 300,
                        (Math.random() - 0.5) * 300,
                        '#8B0000',
                        3000
                    ));
                }
            }
        } catch (error) {
            console.error('创建死亡特效失败:', error);
        }
        
        console.log('Boss被击败!');
    }
    
    checkPhaseTransition() {
        const healthPercent = this.health / this.maxHealth;
        
        if (healthPercent < 0.7 && this.phase === 1) {
            this.phase = 2;
            this.specialAttackCooldown *= 0.8;
            console.log('Boss进入第2阶段!');
        } else if (healthPercent < 0.3 && this.phase === 2) {
            this.phase = 3;
            this.specialAttackCooldown *= 0.6;
            this.speed *= 1.2;
            console.log('Boss进入第3阶段!');
        }
    }
    
    updateMinions(deltaTime, player) {
        this.minions = this.minions.filter(minion => minion.health > 0);
    }
    
    updateAnimation(deltaTime) {
        this.animationTime += deltaTime;
        if (this.animationTime > 200) {
            this.animationFrame = (this.animationFrame + 1) % 8;
            this.animationTime = 0;
        }
    }
    
    updateAura(deltaTime) {
        this.aura.radius = 50 + Math.sin(Date.now() * 0.005) * 10;
    }
    
    createAttackEffect() {
        try {
            if (window.gameEngine && typeof Particle !== 'undefined') {
                for (let i = 0; i < 10; i++) {
                    const angle = (Math.PI * 2 / 10) * i;
                    window.gameEngine.particles.push(new Particle(
                        this.x + Math.cos(angle) * 30,
                        this.y + Math.sin(angle) * 30,
                        Math.cos(angle) * 100,
                        Math.sin(angle) * 100,
                        '#FF4500',
                        800
                    ));
                }
            }
        } catch (error) {
            console.error('创建攻击特效失败:', error);
        }
    }
    
    createSummonEffect() {
        try {
            if (window.gameEngine && typeof Particle !== 'undefined') {
                for (let i = 0; i < 15; i++) {
                    window.gameEngine.particles.push(new Particle(
                        this.x + (Math.random() - 0.5) * 80,
                        this.y + (Math.random() - 0.5) * 80,
                        (Math.random() - 0.5) * 150,
                        -Math.random() * 100,
                        '#800080',
                        1500
                    ));
                }
            }
        } catch (error) {
            console.error('创建召唤特效失败:', error);
        }
    }
    
    addBloodStain() {
        // 血迹效果已禁用
        return;
    }
    
    render(ctx) {
        ctx.save();
        ctx.translate(this.x, this.y);
        
        // 绘制光环
        this.drawAura(ctx);
        
        // 绘制Boss
        this.drawBoss(ctx);
        
        // 绘制血量条
        this.drawBossHealthBar(ctx);
        
        // 绘制阶段指示器
        this.drawPhaseIndicator(ctx);
        
        ctx.restore();
    }
    
    drawAura(ctx) {
        ctx.globalAlpha = this.aura.alpha;
        ctx.fillStyle = this.aura.color;
        ctx.beginPath();
        ctx.arc(0, 0, this.aura.radius, 0, Math.PI * 2);
        ctx.fill();
        ctx.globalAlpha = 1;
    }
    
    drawBoss(ctx) {
        const halfSize = this.size / 2;
        
        // 生成动画
        if (this.state === 'spawning') {
            const spawnProgress = (Date.now() - this.spawnTime) / this.spawnDuration;
            ctx.globalAlpha = spawnProgress;
            const scale = spawnProgress;
            ctx.scale(scale, scale);
        }
        
        // 主体 - 校长僵尸
        ctx.fillStyle = '#2F4F4F';
        ctx.fillRect(-halfSize, -halfSize, this.size, this.size);
        
        // 校长制服
        ctx.fillStyle = '#1C1C1C';
        ctx.fillRect(-halfSize + 5, -halfSize + 10, this.size - 10, this.size - 20);
        
        // 领带
        ctx.fillStyle = '#8B0000';
        ctx.fillRect(-halfSize + 25, -halfSize + 10, 10, 30);
        
        // 恐怖的脸
        ctx.fillStyle = '#8B7D6B';
        ctx.fillRect(-halfSize + 10, -halfSize + 5, this.size - 20, 25);
        
        // 血红眼睛
        ctx.fillStyle = '#FF0000';
        ctx.fillRect(-halfSize + 15, -halfSize + 12, 6, 6);
        ctx.fillStyle = '#FF0000';
        ctx.fillRect(-halfSize + 35, -halfSize + 12, 6, 6);
        
        // 张开的大嘴
        ctx.fillStyle = '#000000';
        ctx.fillRect(-halfSize + 20, -halfSize + 22, 16, 8);
        
        // 尖牙
        ctx.fillStyle = '#FFFFFF';
        ctx.fillRect(-halfSize + 22, -halfSize + 22, 2, 4);
        ctx.fillRect(-halfSize + 26, -halfSize + 22, 2, 4);
        ctx.fillRect(-halfSize + 30, -halfSize + 22, 2, 4);
        ctx.fillRect(-halfSize + 34, -halfSize + 22, 2, 4);
        
        // 爪子
        ctx.fillStyle = '#2F2F2F';
        ctx.fillRect(-halfSize - 8, -halfSize + 20, 12, 6);
        ctx.fillRect(halfSize - 4, -halfSize + 20, 12, 6);
        
        // 血迹
        this.bloodStains.forEach(stain => {
            ctx.globalAlpha = stain.alpha;
            ctx.fillStyle = '#8B0000';
            ctx.fillRect(stain.x - stain.size/2, stain.y - stain.size/2, stain.size, stain.size);
        });
        
        ctx.globalAlpha = 1;
    }
    
    drawBossHealthBar(ctx) {
        const barWidth = 80;
        const barHeight = 8;
        const halfSize = this.size / 2;
        const healthPercent = this.health / this.maxHealth;
        
        // 背景
        ctx.fillStyle = '#333333';
        ctx.fillRect(-barWidth/2, -halfSize - 20, barWidth, barHeight);
        
        // 血量
        ctx.fillStyle = healthPercent > 0.5 ? '#FF4500' : '#FF0000';
        ctx.fillRect(-barWidth/2, -halfSize - 20, barWidth * healthPercent, barHeight);
        
        // 边框
        ctx.strokeStyle = '#FFFFFF';
        ctx.lineWidth = 1;
        ctx.strokeRect(-barWidth/2, -halfSize - 20, barWidth, barHeight);
        
        // Boss名称
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '12px monospace';
        ctx.textAlign = 'center';
        ctx.fillText('校长僵尸', 0, -halfSize - 25);
    }
    
    drawPhaseIndicator(ctx) {
        const halfSize = this.size / 2;
        ctx.fillStyle = '#FFD700';
        ctx.font = '14px monospace';
        ctx.textAlign = 'center';
        ctx.fillText(`阶段 ${this.phase}`, 0, halfSize + 20);
    }
}

// Boss投射物类
class BossProjectile {
    constructor(x, y, vx, vy, damage) {
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
        this.damage = damage;
        this.radius = 8;
        this.color = '#FF4500';
        this.trail = [];
        this.maxTrailLength = 8;
        this.life = 3000;
        this.startTime = Date.now();
    }
    
    update(deltaTime) {
        // 添加拖尾
        this.trail.push({ x: this.x, y: this.y });
        if (this.trail.length > this.maxTrailLength) {
            this.trail.shift();
        }
        
        // 更新位置
        this.x += this.vx * deltaTime / 1000;
        this.y += this.vy * deltaTime / 1000;
        
        // 检查生命周期
        return Date.now() - this.startTime < this.life;
    }
    
    render(ctx) {
        ctx.save();
        
        // 绘制拖尾
        this.trail.forEach((point, index) => {
            const alpha = (index + 1) / this.trail.length * 0.7;
            ctx.globalAlpha = alpha;
            ctx.fillStyle = this.color;
            ctx.fillRect(point.x - 3, point.y - 3, 6, 6);
        });
        
        ctx.globalAlpha = 1;
        
        // 绘制投射物
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fill();
        
        // 发光效果 (简化版，避免shadowBlur兼容性问题)
        ctx.globalAlpha = 0.5;
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius + 3, 0, Math.PI * 2);
        ctx.fill();
        ctx.globalAlpha = 1;
        
        ctx.restore();
    }
}